package com.bigknow.appstore.web.app.service.impl;

import com.bigknow.appstore.common.util.ArrayUtils;
import com.bigknow.appstore.web.app.service.IMyAppService;
import com.bigknow.appstore.web.app.vo.AppVO;
import com.bigknow.appstore.web.base.service.IFusionService;
import com.bigknow.appstore.web.console.app.*;
import com.bigknow.fusion.common.inf.server.appstore.FusionHandler;
import org.apache.shiro.SecurityUtils;
import org.apache.tools.ant.util.DateUtils;
import org.bson.types.ObjectId;
import org.mongodb.morphia.Datastore;
import org.mongodb.morphia.query.Query;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by zhangwei on 2016/10/17.
 */
@Service
public class MyAppService implements IMyAppService {

    @Autowired
    private Datastore ds;

    @Autowired
    private IFusionService fusionService;


    @Override
    public boolean favorite(String appId, boolean isFavorite) {
        com.bigknow.appstore.web.base.entity.User user = (com.bigknow.appstore.web.base.entity.User) SecurityUtils.getSubject().getPrincipal();
        Favorite favorite = ds.find(Favorite.class).filter("appId", appId).filter("userId", user == null ? "" : user.getId()).get();
        if (isFavorite) {
            ds.delete(Favorite.class, favorite.getId());
        } else {
            if (favorite == null) {
                Favorite _favorite = new Favorite();
                _favorite.setAppId(appId);
                _favorite.setId(UUID.randomUUID().toString());
                _favorite.setFavorite(true);
                _favorite.setUserId(user.getId());
                ds.save(_favorite);
                return true;
            }
        }
        return false;
    }

    @Override
    public List<AppVO> getMyAppsByCondition(String[] tags, String orderType, String _state) {
        AppSortType type = AppSortType.valueOf(orderType);
        List<Application> apps = new ArrayList<Application>();
        if (type == AppSortType.HOT) {
            apps = ds.find(Application.class).filter("state", ApplicationState.PUBLISHED).order("-subscribeCount").asList();
        } else if (type == AppSortType.NEW) {
            apps = ds.find(Application.class).filter("state", ApplicationState.PUBLISHED).order("-publishedTime").asList();
        } else {
            apps = ds.find(Application.class).filter("state", ApplicationState.PUBLISHED).order("-star").asList();
        }
        List<AppVO> appVOs = new ArrayList<AppVO>();
        List<Application> results = filterApps(apps, tags);

        SubscribeState state = SubscribeState.valueOf(_state);
        if (SubscribeState.APPLYING == state || SubscribeState.SUCCESS == state) {
            //审批成功
            List<Subscriber> subs = ds.find(Subscriber.class).filter("state", state).filter("user", (com.bigknow.appstore.web.base.entity.User) SecurityUtils.getSubject().getPrincipal()).asList();
            List<String> appIds = new ArrayList<String>();
            for (Subscriber sub : subs) {
                appIds.add(sub.getApplication().getId());
            }
            for (Application app : results) {
                if (appIds.contains(app.getId())) {
                    AppVO vo = new AppVO();
                    vo.setId(app.getId());
                    vo.setName(app.getName());
                    vo.setCategory(ds.find(ApplicationCategory.class).filter("id", app.getCategoryId()).get().getName());
                    vo.setDesc(app.getDescription());
                    vo.setPic(app.getLogoFile());
                    vo.setPublishTime(DateUtils.format(app.getPublishedTime(), com.bigknow.appstore.auth.infrastructure.DateUtils.DATE_FORMAT));
                    vo.setStar(app.getStar());
                    vo.setSubscribeCount(app.getSubscribeCount());
                    appVOs.add(vo);
                }
            }
        } else {
            //TODO 审批失败
        }
        return appVOs;
    }

    private List<Application> filterApps(List<Application> apps, String[] tagIds) {
        if (tagIds != null && tagIds.length > 0) {
            List<Application> results = new ArrayList<Application>();
            for (Application app : apps) {
                for (String tagId : tagIds) {
                    if (app.getTags().contains(tagId)) {
                        results.add(app);
                        break;
                    }
                }
            }
            return results;
        } else {
            return apps;
        }
    }

    @Override
    public List<AppVO> getFavoriteAppsByCondition(String[] tags, String orderType) {
        AppSortType type = AppSortType.valueOf(orderType);
        List<Application> apps = new ArrayList<Application>();

        if (type == AppSortType.HOT) {
            apps = ds.find(Application.class).filter("state", ApplicationState.PUBLISHED).order("-subscribeCount").asList();
        } else if (type == AppSortType.NEW) {
            apps = ds.find(Application.class).filter("state", ApplicationState.PUBLISHED).order("-publishedTime").asList();
        } else {
            apps = ds.find(Application.class).filter("state", ApplicationState.PUBLISHED).order("-star").asList();
        }

        List<AppVO> appVOs = new ArrayList<AppVO>();
        List<Application> results = filterApps(apps, tags);

        List<Favorite> favorites = ds.find(Favorite.class).filter("userId", ((com.bigknow.appstore.web.base.entity.User) SecurityUtils.getSubject().getPrincipal()).getId()).asList();
        List<String> appIds = new ArrayList<String>();
        for (Favorite favorite : favorites) {
            appIds.add(favorite.getAppId());
        }
        for (Application app : results) {
            if (appIds.contains(app.getId())) {
                AppVO vo = new AppVO();
                vo.setId(app.getId());
                vo.setName(app.getName());
                vo.setCategory(ds.find(ApplicationCategory.class).filter("id", app.getCategoryId()).get().getName());
                vo.setDesc(app.getDescription());
                vo.setPic(app.getLogoFile());
                vo.setPublishTime(DateUtils.format(app.getPublishedTime(), com.bigknow.appstore.auth.infrastructure.DateUtils.DATE_FORMAT));
                vo.setStar(app.getStar());
                vo.setSubscribeCount(app.getSubscribeCount());
                appVOs.add(vo);
            }
        }
        return appVOs;
    }

    @Override
    public void applySubscriber(String[] dataNodeIds, String appId) {
        Application app = ds.find(Application.class).filter("id", appId).get();
        com.bigknow.appstore.web.base.entity.User user = (com.bigknow.appstore.web.base.entity.User) SecurityUtils.getSubject().getPrincipal();
        List<SubscribeState> states = new ArrayList<SubscribeState>();
        states.add(SubscribeState.APPLYING);
        states.add(SubscribeState.SUCCESS);
        Subscriber old = ds.find(Subscriber.class).filter("application", app).filter("user", user).filter("state in ",states).get();
        if (old == null) {
            Subscriber sub = new Subscriber();
            sub.setApplication(app);
            sub.setState(SubscribeState.APPLYING);
            sub.setDataNodeIds(Arrays.asList(dataNodeIds));
            sub.setUser(user);
            sub.setId(UUID.randomUUID().toString());
            sub.setSubscribeTime(DateUtils.format(new Date().getTime(), com.bigknow.appstore.auth.infrastructure.DateUtils.DATE_FORMAT));
            ds.save(sub);
        } else {
            FusionHandler handler = fusionService.getFusionHandler();
            if (dataNodeIds.length > 0) {
                for (String id : old.getApplication().getServiceIds()) {
                    //发送数据节点申请
                    handler.sendDataNodeApply(Arrays.asList(dataNodeIds), id, "应用商店平台管理员申请数据节点访问权限，服务ID：[" + id + "],数据节点ID：[" + dataNodeIds + "]", old.getReplyUserId());
                }
            }
        }

    }
}
